package org.apogee.mil.client.main.pages.trainee.widgets;

import java.util.ArrayList;

import org.apogee.mil.client.factories.ServerServiceFactory;
import org.apogee.mil.client.utils.Session;
import org.apogee.mil.shared.Constants.TestFields;
import org.apogee.mil.shared.User;

import com.extjs.gxt.ui.client.data.BaseModel;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;

public class PrevTestsWidget implements IsWidget {
	private ListStore<BaseModel> store = new ListStore<BaseModel>();
	private ColumnModel cm;
	private Grid<BaseModel> grid;
	private int userId;
	private User currentUser;
	private boolean showHeader;
	
	public PrevTestsWidget(int userId) {
		this.currentUser = ServerServiceFactory.getUser(Session.getSessionId());
		this.userId = userId;
		showHeader = userId == -1 ? true : false;
	}
	
	@Override
	public Widget asWidget() {
		
		ContentPanel cp = new ContentPanel();
		cp.setAutoHeight(true);
		cp.setWidth(310);
		cp.setHeading("Previous Tests");
		cp.setHeaderVisible(showHeader);
		cp.setBorders(true);
		
		updateStore(userId);
		
		GridCellRenderer<BaseModel> renderer = new GridCellRenderer<BaseModel>() {

			@Override
			public Object render(BaseModel model, String property, ColumnData config,
					int rowIndex, int colIndex, ListStore<BaseModel> store,
					Grid<BaseModel> grid) {

				String val = (String) (model.get(property) == null ? "No Tests..." : model.get(property));
				return "<span qtitle='" + cm.getColumnById(property).getHeader() + "' qtip='" + val  
						+ "' style='font-weight: bold;color: #5d8aa8'>" + val + "</span>";
			}
		};

		ArrayList<ColumnConfig> configs = new ArrayList<ColumnConfig>();
		ColumnConfig column = new ColumnConfig();
		column.setId(TestFields.TEST_TAKEN);
		column.setHeader("Test");
		column.setWidth(100);
		column.setRowHeader(true);
		column.setRenderer(renderer);
		configs.add(column);

		column = new ColumnConfig();
		column.setId(TestFields.SCORE);
		column.setHeader("Score");
		column.setWidth(100);
		column.setRowHeader(true);
		column.setRenderer(renderer);
		configs.add(column);

		column = new ColumnConfig();
		column.setId(TestFields.DATE_TAKEN);
		column.setHeader("Date");
		column.setWidth(100);
		column.setRowHeader(true);
		column.setRenderer(renderer);
		configs.add(column);

		cm = new ColumnModel(configs);

		grid = new Grid<BaseModel>(store, cm);
		grid.setBorders(true);
		grid.setColumnLines(true);
		grid.getAriaSupport().setLabelledBy(cp.getHeader().getId()+"-label");
		grid.setSize(310, 400);
		
		
		cp.add(grid);
		
		return cp;
	}

	public void update(String selectedTrainee) {
		String val = selectedTrainee.substring(0, selectedTrainee.indexOf("-")).trim();
		int id = -1;
		try {
			id = Integer.valueOf(val);
		} catch (Exception ex) {
			GWT.log("Number format exception. Val = " + val);
			id = -1;
		}
		updateStore(id);		
	}
	
	private void updateStore(int traineeId) {
		if (traineeId != -1) {
			ServerServiceFactory.getTraineeService(currentUser.getSessionId()).getRecentScores(traineeId, new AsyncCallback<ArrayList<BaseModel>>() {

				@Override
				public void onSuccess(ArrayList<BaseModel> result) {
					if (result.size() == 0) {
						MessageBox.alert("Error", "Unable to retreive scores", null);
						return;
					}
					if (grid != null && grid.getStore() != null) {
						grid.getStore().removeAll();
						grid.getStore().add(result);
						grid.getView().refresh(true);
					}			
				}

				@Override
				public void onFailure(Throwable caught) {
					MessageBox.alert("Error", "An exception was thrown when trying to retreive scores", null);

				}
			});
		}
	}
}
